package com.obggtc.picture.service.ai.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.obggtc.picture.config.AliyunAiConfig;
import com.obggtc.picture.dto.ai.AiChatRequest;
import com.obggtc.picture.dto.ai.AiChatResponse;
import com.obggtc.picture.enums.AiProviderEnum;
import com.obggtc.picture.service.ai.AiProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 阿里云通义千问AI服务实现
 * 使用DashScope API进行集成
 * 
 * @author system
 * @date 2025/09/29
 */
@Slf4j
@Service
public class AliyunAiProvider implements AiProvider {
    
    @Autowired
    private AliyunAiConfig aliyunAiConfig;
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    @Override
    public AiProviderEnum getProviderType() {
        return AiProviderEnum.ALIYUN_TONGYI;
    }
    
    @Override
    public AiChatResponse chat(AiChatRequest request) {
        try {
            log.info("使用阿里云通义千问AI处理聊天请求，消息：{}", request.getMessage());
            
            // 参数校验
            if (request == null || !StringUtils.hasText(request.getMessage())) {
                return AiChatResponse.error("消息内容不能为空");
            }
            
            // 检查服务配置
            if (!isServiceAvailable()) {
                return AiChatResponse.error("阿里云通义千问AI服务配置不完整，请检查配置");
            }
            
            // 调用阿里云通义千问API
            String aiResponse = callAliyunApi(request);
            
            if (StringUtils.hasText(aiResponse)) {
                AiChatResponse response = AiChatResponse.success(aiResponse, request.getSessionId());
                log.info("阿里云通义千问AI响应成功，会话ID：{}", request.getSessionId());
                return response;
            } else {
                return AiChatResponse.error("阿里云通义千问AI服务暂时不可用，请稍后再试");
            }
            
        } catch (Exception e) {
            log.error("阿里云通义千问AI聊天服务异常", e);
            return AiChatResponse.error("阿里云通义千问AI服务异常：" + e.getMessage());
        }
    }
    
    @Override
    public boolean isServiceAvailable() {
        return aliyunAiConfig != null 
            && StringUtils.hasText(aliyunAiConfig.getAccessKeyId())
            && StringUtils.hasText(aliyunAiConfig.getAccessKeySecret())
            && !aliyunAiConfig.getAccessKeyId().equals("your-access-key-id")
            && !aliyunAiConfig.getAccessKeySecret().equals("your-access-key-secret");
    }
    
    @Override
    public boolean testConnection() {
        try {
            AiChatRequest testRequest = new AiChatRequest();
            testRequest.setMessage("测试连接");
            testRequest.setMaxTokens(10);
            
            AiChatResponse response = chat(testRequest);
            return response.getCode() == 200 && StringUtils.hasText(response.getContent());
        } catch (Exception e) {
            log.error("阿里云通义千问AI连接测试失败", e);
            return false;
        }
    }
    
    /**
     * 调用阿里云通义千问API
     * 
     * @param request 聊天请求
     * @return AI响应内容
     */
    private String callAliyunApi(AiChatRequest request) {
        try {
            log.info("开始调用阿里云通义千问API，模型：{}", aliyunAiConfig.getModel());
            
            // 构建请求URL
            String apiUrl = "https://" + aliyunAiConfig.getEndpoint() + "/api/v1/services/aigc/text-generation/generation";
            
            // 构建请求头 - 使用简化的API Key认证方式
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + aliyunAiConfig.getAccessKeyId()); // 简化认证
            headers.set("X-DashScope-SSE", "disable"); // 禁用流式响应
            
            // 构建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("model", aliyunAiConfig.getModel());
            
            // 构建input参数
            JSONObject input = new JSONObject();
            
            // 构建消息数组
            JSONArray messages = new JSONArray();
            
            // 如果有系统角色，先添加系统消息
            if (StringUtils.hasText(request.getSystemRole())) {
                JSONObject systemMessage = new JSONObject();
                systemMessage.put("role", "system");
                systemMessage.put("content", request.getSystemRole());
                messages.add(systemMessage);
            }
            
            // 添加用户消息
            JSONObject userMessage = new JSONObject();
            userMessage.put("role", "user");
            userMessage.put("content", request.getMessage());
            messages.add(userMessage);
            
            input.put("messages", messages);
            requestBody.put("input", input);
            
            // 构建parameters参数
            JSONObject parameters = new JSONObject();
            if (request.getTemperature() != null) {
                parameters.put("temperature", request.getTemperature());
            }
            if (request.getMaxTokens() != null) {
                parameters.put("max_tokens", request.getMaxTokens());
            }
            // 通义千问特有参数
            parameters.put("result_format", "message"); // 消息格式返回
            if (!parameters.isEmpty()) {
                requestBody.put("parameters", parameters);
            }
            
            HttpEntity<String> entity = new HttpEntity<>(requestBody.toJSONString(), headers);
            
            log.info("发送请求到阿里云通义千问API，消息长度：{}", request.getMessage().length());
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                apiUrl,
                HttpMethod.POST,
                entity,
                String.class
            );
            
            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject responseJson = JSON.parseObject(response.getBody());
                
                // 检查是否有错误
                if (responseJson.containsKey("code") && !responseJson.getString("code").equals("200")) {
                    String errorMessage = responseJson.getString("message");
                    log.error("阿里云通义千问API返回错误：{}", errorMessage);
                    throw new RuntimeException("阿里云通义千问API错误：" + errorMessage);
                }
                
                // 解析正常响应
                JSONObject output = responseJson.getJSONObject("output");
                if (output != null) {
                    JSONArray choices = output.getJSONArray("choices");
                    if (choices != null && choices.size() > 0) {
                        JSONObject firstChoice = choices.getJSONObject(0);
                        JSONObject message = firstChoice.getJSONObject("message");
                        String content = message.getString("content");
                        
                        log.info("阿里云通义千问API调用成功，响应长度：{}", content != null ? content.length() : 0);
                        return content;
                    }
                    
                    // 如果choices为空，尝试获取text字段
                    String text = output.getString("text");
                    if (StringUtils.hasText(text)) {
                        log.info("阿里云通义千问API调用成功（text格式），响应长度：{}", text.length());
                        return text;
                    }
                }
                
                log.warn("阿里云通义千问API响应为空");
                return null;
            } else {
                log.error("阿里云通义千问API调用失败，状态码：{}", response.getStatusCode());
                throw new RuntimeException("阿里云通义千问API调用失败，状态码：" + response.getStatusCode());
            }
            
        } catch (Exception e) {
            log.error("调用阿里云通义千问API时发生异常", e);
            if (e.getMessage().contains("401") || e.getMessage().contains("Unauthorized")) {
                throw new RuntimeException("阿里云通义千问API密钥配置错误，请检查AccessKey");
            } else if (e.getMessage().contains("429")) {
                throw new RuntimeException("阿里云通义千问API调用频率超限，请稍后再试");
            } else if (e.getMessage().contains("400")) {
                throw new RuntimeException("阿里云通义千问API请求参数错误，请检查请求格式");
            } else {
                throw new RuntimeException("阿里云通义千问AI服务调用异常：" + e.getMessage());
            }
        }
    }
}
